package com.ltmm;

import com.alibaba.fastjson.JSONObject;
import okhttp3.*;

import java.io.IOException;

import com.alibaba.fastjson.*;

public class MyRequest {
    private String BaseURL = "http://10.10.2.12:8080/";
    private String OauthURL = BaseURL + "oauth2/client/v1/accessToken";
    HttpUrl.Builder urlBuilder;
    String Token = "";
    OkHttpClient client = new OkHttpClient();

    private String grantType = "client_credential";
//    private String appid = "App_79945ce5a7fc434198b2d5ce684eb6ff";
//    private String secret = "b32094811d9a565ad530825c7824dcfe";

    /**
     * 根据 BaseURL grantType appid secret 创建MyRequest
     * @param BaseURL
     * @param appid
     * @param secret
     */
    public MyRequest(String BaseURL,String appid,String secret){
        this.BaseURL = BaseURL;
        OauthURL = BaseURL + "oauth2/client/v1/accessToken";

        urlBuilder = HttpUrl.parse(OauthURL).newBuilder();
        urlBuilder.addQueryParameter("grantType", grantType);
        urlBuilder.addQueryParameter("appid", appid);
        urlBuilder.addQueryParameter("secret", secret);
    }

    /**
     * 根据 grantType appid secret 创建MyRequest
     * @param appid
     * @param secret
     */
    public MyRequest(String appid,String secret){
        urlBuilder = HttpUrl.parse(OauthURL).newBuilder();
        urlBuilder.addQueryParameter("grantType", grantType);
        urlBuilder.addQueryParameter("appid", appid);
        urlBuilder.addQueryParameter("secret", secret);
    }


    String getOathString() throws IOException {
        Request request = new Request.Builder()
                .url(urlBuilder.build())
                .build();
        try (Response response = client.newCall(request).execute()) {
            JSONObject responseObject = JSON.parseObject(response.body().string());
            Token = responseObject.getString("accessToken");
            return Token;
        }
    }

    // url： baseURL + /api/runtime/objects/$objectName/debugServices/$serviceName
    // Content-Type: application/json
    // Authorization: Bearer $accessToken
    // methods: POST
    // raw: {
    //      serviceInput
    // }
    public JSONObject excueteServie(String objectName, String serviceName, String inputJson){
        String urlTempLate = BaseURL + "api/runtime/objects/%s/debugServices/%s";
        String url = String.format(urlTempLate, objectName, serviceName);
        RequestBody body = RequestBody.create(
                inputJson.replaceAll("\'", "\""),
                MediaType.get("application/json; charset=utf-8")
        );
        Request request = new Request.Builder().url(url)
                .addHeader("Authorization", String.format("Bearer %s", Token))
                .post(body).build();
        try (Response response = client.newCall(request).execute()) {
            if (response.code() == 401) {
                System.out.println("code:401 获取Token中");
                getOathString();
                JSONObject object = excueteServie(objectName, serviceName, inputJson);
                if (object == null) {
                    System.out.println("重试失败");
                }
                return object;
            } else if (response.code() == 200) {
                JSONObject responseObject = JSON.parseObject(response.body().string());
                return responseObject.getJSONObject("result");
            } else {
                System.out.println(response.code());
                return null;
            }
        } catch (Exception e) {
            System.out.println("Exception:网络错误");
            return null;
        }
    }

//
//    public static void main(String[] args) throws IOException {
//        JSONObject data1 = MyRequest.excueteServie("AnyLogic_params", "getParms", "{\"name\":\"to2\"}");
//        JSONObject data2 = MyRequest.excueteServie("AnyLogic_params", "getParms", "{\"name\":\"to1\"}");
//        JSONObject data3 = MyRequest.excueteServie("AnyLogic_params", "getParms", "{'name':'to1,to2'}");
//
//        System.out.println(data1.get("to2"));
//        System.out.println(data2);
//        System.out.println(data3);
//        JsonFactory jsonFactory = new JsonFactory();
//        jsonFactory
//                .put("name","毛嘉敏")
//                .put("sex",0)
//                .put("numbers",new int[]{1,2,3})
//                .put("english","litangmm");
//        System.out.println(jsonFactory.build());
//    }
}
